﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Usido.CRM.Core.Extensions;
using Usido.CRM.Core.ToolHelper;
using Usido.CRM.IRepository;
using Usido.CRM.Models;
using Usido.CRM.Repository;

namespace Usido.CRM.App.Forms
{
    public partial class YG_SetFrom : Form
    {
        public YG_SetFrom()
        {
            InitializeComponent();
        }
        #region 窗体绘制
        /// <summary>
        /// 解决加载窗体多控件所造成的闪烁 
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                return cp;
            }
        }
        #endregion
        public YG_SetFrom(string userId)
        {
            InitializeComponent();
            this.userId = userId;
        }

        private readonly ISysRoleRepository Roles = new SysRoleRepository();
        private readonly ISysUserRepository userReposioty = new SysUserRepository();
        private readonly ISysLogRepository SysLog = new SysLogRepository();
        private readonly ISysDepartmentRepository departmentReposit = new SysDepartmentRepository();//部门字典
        private readonly ISysDictRepository DictReposit = new SysDictRepository();//学历字典
        private string userId;

        private void toolStripDropDownButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }



        #region 根据姓名填充简拼
        private void TB_Name_Leave(object sender, EventArgs e)
        {
            if (TB_Name.Text.Length > 0)
            {
                TB_Jm.Text = "";
                for (int i = 0; i < TB_Name.Text.Length; i++)
                {

                    TB_Jm.Text += Tools.GetPYChar(TB_Name.Text.Substring(i, 1).Trim());
                }
            }
            else
            {
                TB_Jm.Text = "";
            }
        }
        #endregion

        #region 根据身份证号自动填充生日和性别
        private void TB_Sfzmhm_Leave(object sender, EventArgs e)
        {
            string identityCard = TB_Sfzmhm.Text.Trim();
            if (string.IsNullOrEmpty(identityCard))
            {
                //身份证号码不能为空，如果为空返回
                MessageBox.Show("身份证号码不能为空！");
                if (TB_Sfzmhm.CanFocus)
                {
                    TB_Sfzmhm.Focus();
                }
                return;
            }
            else
            {
                //身份证号码只能为15位或18位其它不合法
                if (identityCard.Length != 15 && identityCard.Length != 18)
                {
                    MessageBox.Show("身份证号码为15位或18位，请检查！");
                    if (TB_Sfzmhm.CanFocus)
                    {
                        TB_Sfzmhm.Focus();
                    }
                    return;
                }
            }
            string birthday = "";
            string sex = "";
            //处理18位的身份证号码从号码中得到生日和性别代码
            if (identityCard.Length == 18)
            {
                birthday = identityCard.Substring(6, 4) + "-" + identityCard.Substring(10, 2) + "-" + identityCard.Substring(12, 2);
                sex = identityCard.Substring(14, 3);
            }
            //处理15位的身份证号码从号码中得到生日和性别代码
            if (identityCard.Length == 15)
            {
                birthday = "19" + identityCard.Substring(6, 2) + "-" + identityCard.Substring(8, 2) + "-" + identityCard.Substring(10, 2);
                sex = identityCard.Substring(12, 3);
            }
            Tb_Csrq.Text = birthday;
            //性别代码为偶数是女性奇数为男性
            if (int.Parse(sex) % 2 == 0)
            {
                this.TB_Sex.Text = "女";
            }
            else
            {
                this.TB_Sex.Text = "男";
            }

        }
        #endregion



        private void YG_SetFrom_Load(object sender, EventArgs e)
        {
            DGV_userList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            this.DGV_userList.AutoGenerateColumns = false;
            GetAllUsers();
            #region 部门下拉框
            var List_SysDepartment = departmentReposit.GetList();
            CoB_Bm.DataSource = List_SysDepartment;
            CoB_Bm.ValueMember = nameof(SysDepartment.Id);
            CoB_Bm.DisplayMember = nameof(SysDepartment.DeptName);
            CoB_Bm.SelectedIndex = -1;
            #endregion
            #region 学历下拉框
            var List_SysDictReposit = DictReposit.GetList(new { dicttypeid = 1 });
            CoB_Xl.DataSource = List_SysDictReposit;
            CoB_Xl.ValueMember = nameof(SysDict.Id);
            CoB_Xl.DisplayMember = nameof(SysDict.DictName);
            CoB_Xl.SelectedIndex = -1;
            #endregion
            #region 角色下拉框

            var List_roles = Roles.GetList();
            CoB_JS.DataSource = List_roles;
            CoB_JS.ValueMember = nameof(SysRole.Id);
            CoB_JS.DisplayMember = nameof(SysRole.RoleName);
            CoB_JS.SelectedIndex = -1;
            #endregion
        }

        private void DGV_userList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
               e.RowBounds.Location.Y,
               DGV_userList.RowHeadersWidth - 4,
               e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics,
                  (e.RowIndex + 1).ToString(),
                   DGV_userList.RowHeadersDefaultCellStyle.Font,
                   rectangle,
                   DGV_userList.RowHeadersDefaultCellStyle.ForeColor,
                   TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
            Users_count.Text = "员工总数：" + (DGV_userList.Rows.Count).ToString() + " ";
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string Str = textBox1.Text.Trim();
            int state = 0;
            try
            {
                if (!int.TryParse(Str, out state))
                {
                    var List_Users = userReposioty.GetUserList($" (username like '%{Str}%'  or UserLogogramCode like '%{Str}%') and a.Id<>10000  ");
                    DGV_userList.DataSource = List_Users;
                }
                else
                {
                    var List_Users = userReposioty.GetUserList($" (username like '%{Str}%'  or UserLogogramCode like '%{Str}%' or a.State={Str}) and a.Id<>10000  ");
                    DGV_userList.DataSource = List_Users;
                }
            }
            catch (Exception)
            {

                GetAllUsers();
            }
        }

        /// <summary>
        /// 查询所有员工
        /// </summary>
        private void GetAllUsers()
        {
            var List_Users = userReposioty.GetUserList(" a.State=1 and a.Id<>10000 ");
            DGV_userList.DataSource = List_Users;
        }
        /// <summary>
        /// 新增员工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripDropDownButton1_Click(object sender, EventArgs e)
        {
            初始化控件值();
            this.tabControl1.SelectedIndex = 1;
        }

        private void 初始化控件值()
        {
            TB_Name.Text = "";
            TB_Jm.Text = "";
            TB_Bm.Text = "";
            TB_Sfzmhm.Text = "";
            TB_Sex.Text = "";
            CheckBT_zt.Checked = false;
            Tb_Csrq.Text = "";
            CoB_Bm.SelectedIndex = -1;
            CoB_Xl.SelectedIndex = -1;
            CoB_JS.SelectedIndex = -1;
            DateTimeTB_Rzrq.Text = DateTime.Now.ToString("yyyy年MM月dd日");
            TB_Tel.Text = "";
            this.tabControl1.SelectedIndex = 0;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripDropDownButton4_Click(object sender, EventArgs e)
        {
            string Id = DGV_userList.SelectedRows[0].Cells["用户编号"].Value.ToString();
            string name = DGV_userList.SelectedRows[0].Cells["用户姓名"].Value.ToString();
            DialogResult RSS = MessageBox.Show(this, $"确定要删除员工{name}？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (RSS == DialogResult.Yes)
            {
                int res = userReposioty.Delete(int.Parse(Id));
                if (res > 0)
                {
                    string LogStr = $"删除{name}成功";
                    SysLog.AddLog(int.Parse(Id), LogStr);
                    MessageBox.Show(LogStr);
                }
            }
            GetAllUsers();
        }
        /// <summary>
        /// 员工修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripDropDownButton3_Click(object sender, EventArgs e)
        {
            try
            {
                string Id = DGV_userList.SelectedRows[0].Cells["用户编号"].Value.ToString();
                string name = DGV_userList.SelectedRows[0].Cells["用户姓名"].Value.ToString();
                var UserInfo = userReposioty.GetUserList($"a.id='{Id}'");
                TB_Name.Text = name;
                TB_Jm.Text = UserInfo.ToList()[0].UserLogogramCode;
                TB_Bm.Text = UserInfo.ToList()[0].Id.ToString();
                TB_Sfzmhm.Text = UserInfo.ToList()[0].IdNumber;
                if (UserInfo.ToList()[0].Sex)
                {
                    TB_Sex.Text = "男";
                }
                else
                {
                    TB_Sex.Text = "女";
                }
                if (UserInfo.ToList()[0].State == "1")
                {
                    CheckBT_zt.Checked = false;
                }
                else
                {
                    CheckBT_zt.Checked = true;
                }
                CoB_JS.Text = UserInfo.ToList()[0].RoleName;
                if (UserInfo.ToList()[0].Birthdate != null)
                {
                    Tb_Csrq.Text = ((DateTime)UserInfo.ToList()[0].Birthdate).ToString("yyyy年MM月dd日");
                }
                CoB_Bm.Text = UserInfo.ToList()[0].DeptName;
                CoB_Xl.Text = UserInfo.ToList()[0].DictName;
                DateTimeTB_Rzrq.Text = UserInfo.ToList()[0].TakingWorkTime.ToString();
                TB_Tel.Text = UserInfo.ToList()[0].Contact;
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选择员工!");
            }
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(TB_Bm.Text.Trim()))
            {
                SysUser u = new SysUser();
                if (string.IsNullOrEmpty(TB_Name.Text.Trim()) || string.IsNullOrEmpty(TB_Jm.Text.Trim()) || string.IsNullOrEmpty(TB_Sfzmhm.Text.Trim()) || string.IsNullOrEmpty(TB_Sex.Text.Trim()) || string.IsNullOrEmpty(Tb_Csrq.Text.Trim()) || string.IsNullOrEmpty(CoB_Bm.Text.Trim()) || string.IsNullOrEmpty(DateTimeTB_Rzrq.Text.Trim()) || string.IsNullOrEmpty(CoB_Xl.Text.Trim()) || string.IsNullOrEmpty(TB_Tel.Text.Trim()))
                {
                    MessageBox.Show("请完善信息再保存!");
                }
                else
                {
                    u.UserName = TB_Name.Text.Trim();
                    u.Password = "123456".ToMd5String();
                    u.UserLogogramCode = TB_Jm.Text.Trim();
                    u.IdNumber = TB_Sfzmhm.Text.Trim();
                    if (TB_Sex.Text == "男")
                    {
                        u.Sex = true;
                    }
                    else
                    {
                        u.Sex = false;
                    }
                    try
                    {
                        u.Birthdate = DateTime.Parse(Tb_Csrq.Text.Trim());
                    }
                    catch (Exception)
                    {

                    }
                    u.DeptId = int.Parse(CoB_Bm.SelectedValue.ToString());
                    u.TakingWorkTime = DateTimeTB_Rzrq.Value;
                    u.EqucationId = int.Parse(CoB_Xl.SelectedValue.ToString());
                    u.Contact = TB_Tel.Text.Trim();
                    u.CreateTime = DateTime.Now;
                    if (CheckBT_zt.Checked)
                    {
                        u.State = false;
                    }
                    else
                    {
                        u.State = true;
                    }
                    u.RoleId = int.Parse(CoB_JS.SelectedValue.ToString());
                    if (userReposioty.Insert(u) > 0)
                    {
                        SysLog.AddLog(Convert.ToInt32(userId), $"添加员工{ u.UserName}完成", u);
                        MessageBox.Show("新增成功!");
                        GetAllUsers();
                        初始化控件值();
                    }
                    else
                    {
                        MessageBox.Show("保存失败!");
                    }
                }
            }
            else
            {
                string id = TB_Bm.Text;
                if (string.IsNullOrEmpty(TB_Name.Text.Trim()) || string.IsNullOrEmpty(TB_Jm.Text.Trim()) || string.IsNullOrEmpty(TB_Sfzmhm.Text.Trim()) || string.IsNullOrEmpty(TB_Sex.Text.Trim()) || string.IsNullOrEmpty(Tb_Csrq.Text.Trim()) || string.IsNullOrEmpty(CoB_Bm.Text.Trim()) || string.IsNullOrEmpty(DateTimeTB_Rzrq.Text.Trim()) || string.IsNullOrEmpty(CoB_Xl.Text.Trim()) || string.IsNullOrEmpty(TB_Tel.Text.Trim()) || string.IsNullOrEmpty(CoB_JS.Text.Trim()))
                {
                    MessageBox.Show("请完善信息再保存!");
                    return;
                }
                //DialogResult RSS = MessageBox.Show(this, "确定要更新员工信息吗", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                //if (RSS == DialogResult.Yes)
                //{
                var UserInfo = userReposioty.Get(id.ToInt());
                UserInfo.UserName = TB_Name.Text.Trim();
                UserInfo.UserLogogramCode = TB_Jm.Text.Trim();
                UserInfo.IdNumber = TB_Sfzmhm.Text.Trim();
                if (TB_Sex.Text == "男")
                {
                    UserInfo.Sex = true;
                }
                else
                {
                    UserInfo.Sex = false;
                }
                UserInfo.Birthdate = DateTime.Parse(Tb_Csrq.Text.Trim());
                UserInfo.DeptId = int.Parse(CoB_Bm.SelectedValue.ToString());
                UserInfo.TakingWorkTime = DateTimeTB_Rzrq.Value;
                UserInfo.EqucationId = int.Parse(CoB_Xl.SelectedValue.ToString());
                UserInfo.Contact = TB_Tel.Text.Trim();
                if (CheckBT_zt.Checked)
                {
                    UserInfo.State = false;
                }
                else
                {
                    UserInfo.State = true;
                }
                UserInfo.RoleId = int.Parse(CoB_JS.SelectedValue.ToString());
                if (userReposioty.Update(UserInfo) > 0)
                {
                    SysLog.AddLog(Convert.ToInt32(userId), "更新员工完成", UserInfo);
                    MessageBox.Show("修改成功!");
                    this.tabControl1.SelectedIndex = 0;
                    GetAllUsers();
                    初始化控件值();
                }
                else
                {
                    MessageBox.Show("保存失败!");
                }
                // }
            }
        }


        private void DGV_userList_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                string Id = DGV_userList.SelectedRows[0].Cells["用户编号"].Value.ToString();
                string name = DGV_userList.SelectedRows[0].Cells["用户姓名"].Value.ToString();
                var UserInfo = userReposioty.GetUserList($"a.id='{Id}'");
                TB_Name.Text = name;
                TB_Jm.Text = UserInfo.ToList()[0].UserLogogramCode;
                TB_Bm.Text = UserInfo.ToList()[0].Id.ToString();
                TB_Sfzmhm.Text = UserInfo.ToList()[0].IdNumber;
                if (UserInfo.ToList()[0].Sex)
                {
                    TB_Sex.Text = "男";
                }
                else
                {
                    TB_Sex.Text = "女";
                }
                if (UserInfo.ToList()[0].State == "可用")
                {
                    CheckBT_zt.Checked = false;
                }
                else
                {
                    CheckBT_zt.Checked = true;
                }
                CoB_JS.Text = UserInfo.ToList()[0].RoleName;

                if (UserInfo.ToList()[0].Birthdate != null)
                {
                    Tb_Csrq.Text = ((DateTime)UserInfo.ToList()[0].Birthdate).ToString("yyyy年MM月dd日");
                }
                CoB_Bm.Text = UserInfo.ToList()[0].DeptName;
                CoB_Xl.Text = UserInfo.ToList()[0].DictName;
                DateTimeTB_Rzrq.Text = UserInfo.ToList()[0].TakingWorkTime.ToString();
                TB_Tel.Text = UserInfo.ToList()[0].Contact;
                this.tabControl1.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                MessageBox.Show("请选择员工!");
            }
        }
    }
}
